package demo

import (
	"io"
	"log"
	"math"
	"os"

	"gitee.com/general252/ebml-go/core"
	"gitee.com/general252/ebml-go/core/formats"
	"gitee.com/general252/ebml-go/mkv"
	"gitee.com/general252/ebml-go/mkvcore"
	"gitee.com/general252/ebml-go/webm"
	"github.com/bluenviron/mediacommon/pkg/codecs/mpeg4audio"
)

func AACDemo() {
	var inFilename = "output.aac"
	var outFilename = "outAAC.mkv"

	w, err := os.OpenFile(outFilename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
	if err != nil {
		log.Println(err)
		return
	} else {
		defer w.Close()
	}

	ws, err := webm.NewSimpleBlockWriter(w,
		[]*webm.TrackEntry{
			{
				Name:        "Audio",
				TrackNumber: 1,
				TrackUID:    12345,
				CodecID:     core.AudioCodecAAC,
				TrackType:   core.TrackTypeAudio,
				Audio: &webm.Audio{
					SamplingFrequency: 8000,
					Channels:          1,
				},
			},
		},
		mkvcore.WithSeekHead(true),
		mkvcore.WithCues(true),
		mkvcore.WithEBMLHeader(mkv.DefaultEBMLHeader),
		mkvcore.WithSegmentInfo(mkv.DefaultSegmentInfo),
		mkvcore.WithMaxKeyframeInterval(1, math.MaxInt16-5000),
	)

	if err != nil {
		log.Println(err)
		return
	} else {
		defer ws[0].Close()
	}

	audioStream := ws[0]

	/////////////////////////
	var fp io.ReadCloser
	if fp, err = os.Open(inFilename); err != nil {
		log.Println(err)
		return
	} else {
		defer fp.Close()
	}

	var timestamp int64

	formats.EmitADTSReader(fp, func(packet *mpeg4audio.ADTSPacket, data, _ []byte) {
		_, _ = audioStream.Write(true, timestamp, data)
		timestamp += 128
		log.Println(timestamp)
	})

}
